package com.hmdp.service.impl;

import com.hmdp.model.dto.Result;
import com.hmdp.model.dto.UserDTO;
import com.hmdp.model.entity.BlogComments;
import com.hmdp.mapper.BlogCommentsMapper;
import com.hmdp.model.entity.User;
import com.hmdp.service.IBlogCommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IBlogService;
import com.hmdp.utils.ThreadLocalUtls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ghp
 * @since 2021-12-22
 */
@Service
public class BlogCommentsServiceImpl extends ServiceImpl<BlogCommentsMapper, BlogComments> implements IBlogCommentsService {

    @Autowired
    private IBlogService iBlogService;

    @Override
    public Result giveComment(BlogComments blogComments) {
        //1.获取当前用户
        UserDTO user = ThreadLocalUtls.getUser();
        if(user == null){
            return Result.fail("请登录后再评论");
        }
        //2.补全信息
        blogComments.setBlogId(blogComments.getBlogId());
        blogComments.setLiked(0);
        blogComments.setStatus(true);

        //3.将评论数据保存到数据库
        boolean save = save(blogComments);
        if(!save){
            return Result.fail("评论失败");
        }

        iBlogService.update()
                .setSql("comments = comments + 1")
                .eq("id", blogComments.getBlogId())
                .update();

        return Result.ok();
    }
}
